package com.android.zweibo.imgcache;

import java.lang.Thread.State;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.android.zweibo.app.WeiboApplication;

import android.graphics.Bitmap;

public class ImageLoader {
	
	private final static int MESSAGE_ID = 1;
	public final static String EXTRA_IMG_URL = "extra_img_url";
	public final static String EXTRA_IMG = "extra_img";
	
	//image缓存管理
	private ImageCacheManager imageCacheManager = new ImageCacheManager(WeiboApplication.context);
	//存放url的对列
	private BlockingQueue<String> urlQueue = new ArrayBlockingQueue<String>(50);
	//图片下载线程
	private DownloadImageThread downloadImageThread = new DownloadImageThread();
	
	private CallbackManager callbackManager = new CallbackManager();
	
	
	/**
	 * 获取bitmap
	 * @param url
	 * @param callBack
	 * @return
	 */
	public Bitmap get(String url, ImageLoaderCallBack callBack) {
		Bitmap bitmap =ImageCacheManager.getUserDefaultHead;
		if(imageCacheManager.contains(url)) {
			bitmap = imageCacheManager.getFromCache(url);
			return bitmap;
		}else {
			callbackManager.put(url,callBack);
			startDownloadThread(url);
		}		
		return bitmap;
	}
    
	/**
	 * 开启图片下载线程
	 * @param url
	 */
	private void startDownloadThread(String url) {
          putURLToQueue(url);	
          
          State state = downloadImageThread.getState();
          
          if(state == State.NEW) {
        	  downloadImageThread.start();
          }else if(state == State.TERMINATED) {
        	  downloadImageThread = new DownloadImageThread();
        	  downloadImageThread.start();
          }
	}
    
	
	/**
	 * 添加图片url到队列中
	 * @param url
	 */
	private void putURLToQueue(String url) {
		if(!imageCacheManager.contains(url)) {
			try {
				urlQueue.put(url);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 图片下载线程
	 * @author administrator
	 *
	 */
	class DownloadImageThread extends Thread {
		
	}
}
